package com.liaoyifan.core.aspect;

import com.liaoyifan.core.annotation.DistributedLock;
import com.liaoyifan.core.util.Lock;
import com.liaoyifan.core.util.SpELKey;
import java.util.Set;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;

@SuppressWarnings("unused")
@Aspect
@Order(5)
public class DistributedLockAspect {

    private static final Logger log =
            LogManager.getLogger(DistributedLockAspect.class.getSimpleName());

    @Around("@annotation(distributedLock)")
    public Object distributedLockAround(
            ProceedingJoinPoint joinPoint, DistributedLock distributedLock) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Set<String> keys =
                SpELKey.distributedLockKey(signature, joinPoint.getArgs(), distributedLock.value());
        log.info("DistributedLockKey: {}", keys);
        return Lock.lock(
                keys, joinPoint::proceed, distributedLock.waitTime(), distributedLock.leaseTime());
    }
}
